<script setup>
import { reactive, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import planApi from "@/api/planApi";
import JsPdfImg from '@/utils/htmlToPDF'
import dayjs from "dayjs";
import Upload from "@/components/Upload.vue";
import planApplyProjectApi from "@/api/planApplyProjectApi.js";
import constants from "@/utils/constants";
import QrcodeVue from "qrcode.vue";

const exportArrangeTicketVisible = ref(false);
const searchForm = ref();
const historyParams = history.state.params;
let searchModel = reactive({
  planId: historyParams.planId,
  gradeId: "",
  templateStyle: 'normal'
});

const uploadData = ref({
  planId: historyParams.planId
});

const uploadErrorList = ref([]);

let arrangeVisible = ref(false);
const loading = ref(false);
let submiting = ref(false);
let downloading = ref(false);
let exporting = ref(false);


let schoolList = ref([]);
let gradeClassesList = ref([]);
let classesList = ref([]);
const arrangeModel = reactive({
  sexGroup: "1",
  gradeFixGroup: false,
  classFixGroup: true,
  planId: historyParams.planId
});

const exportTicketModel = ref({
  planId: historyParams.planId,
  exportArrangeTicketType: "1"
});

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

const columns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 150,
  },
  {
    title: "分组号",
    dataIndex: "groupNo",
    width: 100,
  },
  {
    title: "报名项目",
    dataIndex: "projectNames",
    width: 300,
    fixed: "right",
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const data = ref([]);

const schoolSelectChange = (schoolId) => {
  if (schoolId) {
    planApi
      .getGradeClassesList({
        planId: historyParams.planId,
        schoolId: schoolId,
      })
      .then((res) => {
        gradeClassesList.value = res;
      });
  } else {
    gradeClassesList.value = [];
    classesList.value = [];
    searchModel.classesId = "";
    searchModel.gradeId = "";
  }
};

const sureArrange = (values) => {
  submiting.value = true;
  planApplyProjectApi.arrange(values).then((res) => {
    Message.success("操作成功");
    search();
    submiting.value = false;
    arrangeVisible.value = false;
  });
}

const showArrangeImportDialog = ref(false);

const showArrangeImport = () => {
  showArrangeImportDialog.value = true;
}

const showArrangeDialog = () => {
  arrangeVisible.value = true;
  submiting.value = false;
  searchModel = {
    planId: historyParams.planId,
    sexGroup: 1,
    classFixGroup: true
  };
};


const deleteRecord = (record) => {
  planApi
    .deleteStudent({
      id: record.id,
    })
    .then((res) => {
      search();
    });
};

const handleExport = async (name) => {
  exporting.value = true;
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  planApplyProjectApi.exportArrange(params).then((res) => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "编排结果-" + dayjs().format("YYYYMMDDHHmmss") + ".zip";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    exporting.value = false;
  })
}

const exportingTicket = ref(false)
const sureExportArrangeTicket = () => {
  exportingTicket.value = true;
  planApplyProjectApi.exportArrangeTicket(exportTicketModel.value).then((res) => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "编排准考证-" + dayjs().format("YYYYMMDDHHmmss") + ".zip";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    exportingTicket.value = false;
    exportArrangeTicketVisible.value = false;
  })
}

const handleExportTicket = () => {
  exportArrangeTicketVisible.value = true;
}

const exportingExcel = ref(false)
const handleExportExcel = () => {
  exportingExcel.value = true;
  planApplyProjectApi.exportArrangeExcel(searchModel).then((res) => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "编排表-" + dayjs().format("YYYYMMDDHHmmss") + ".xlsx";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    exportingExcel.value = false;
  })
}

const downloadToPDF = () => {
  console.log(document.getElementById('pdfRef'))
  var fileName = data.value.length > 0 ? data.value[0].schoolName + '体育中考分组表' : '体育中考分组表'
  new JsPdfImg("#pdfRef", fileName, {
    pageBreak: ['.pdfRef'], // 当导出pdf时候，这个参数必填
    pageStartOffset: 0, // 每个页头的留空距离
    watermarkOption: null,
  }).outPdf(() => {
    console.log('结束')
    exporting.value = false;
  });
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.children && gradeModel.children.length > 0) {
    classesList.value = gradeModel.children;
  } else {
    searchModel.classesId = "";
    classesList.value = [];
  }
};

const getSchoolList = () => {
  planApi
    .getSchoolList({
      planId: historyParams.planId,
    })
    .then((res) => {
      schoolList.value = res;
    });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  planApplyProjectApi.queryArrangePage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search();
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.classesId = "";
  searchModel.gradeId = "";
};


refresh();
getSchoolList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>考试计划</a-breadcrumb-item>
        <a-breadcrumb-item>编排</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="schoolId" label="学校">
                  <a-select v-model="searchModel.schoolId" placeholder="请选择学校" allow-clear @change="schoolSelectChange">
                    <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                      :label="school.name"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="groupNo" label="分组号">
                  <a-input v-model="searchModel.groupNo" placeholder="请输入分组号"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search()">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-card>
      <div class="toolbar flex"
        style="position: sticky;top: 0px;background-color: #fff;padding-top: 10px;border-bottom: 1px solid #e5e5e5;">
        <a-space wrap>
          <a-button type="primary" @click="showArrangeDialog">
            <template #icon>
              <icon-edit />
            </template>
            开始编排
          </a-button>
          <a-button type="primary" @click="showArrangeImport">
            <template #icon>
              <icon-edit />
            </template>
            导入自定义编排
          </a-button>
          <a-button type="outline" :loading="exporting" @click="handleExport">
            <template #icon>
              <icon-download />
            </template>
            导出秩序册
          </a-button>
          <a-button type="outline" :loading="exportingExcel" @click="handleExportExcel">
            <template #icon>
              <icon-download />
            </template>
            导出编排表
          </a-button>
          <a-button type="outline" :loading="exportingTicket" @click="handleExportTicket">
            <template #icon>
              <icon-download />
            </template>
            导出准考证
          </a-button>
          <a-radio-group type="button" v-model="searchModel.templateStyle">
            <a-radio value="normal">统一报项模板</a-radio>
            <a-radio value="custom">非统一报项模板</a-radio>
          </a-radio-group>
        </a-space>
        <div class="flex flex1 flex-v-center flex-end" style="text-align: right;">
          <a-pagination @change="pagination.pageChange" @page-size-change="pagination.pageSizeChange"
            :total="pagination.total" :current="pagination.current" :page-size="pagination.pageSize"
            :page-size-options="pagination.pageSizeOptions" show-total show-page-size />
        </div>
      </div>
      <div style="background-color: #f9f9f9;border-top: 1px solid #e5e5e5;">
        <a-spin :loading="loading" style="width: 100%;">
          <a-empty v-if="data.length == 0"></a-empty>
          <div class="pages" id="pdfRef">
            <div :class="['pdfRef']" :id="'group' + groupItem.groupNo" v-for="groupItem in data"
              :key="groupItem.groupNo">
              <div class="title page-header">{{ groupItem.schoolName }}体育考试分组表</div>
              <div class="flex flex-v-center">
                <div class="flex1">
                  <table style="width: 100%;border: 1px solid #e5e5e5;">
                    <tbody>
                      <tr class="group-info">
                        <td class="td rb">学校名称</td>
                        <td class="td">{{ groupItem.schoolName }}</td>
                      </tr>
                      <tr class="group-info">
                        <td class="td rb">校内组号</td>
                        <td class="td">{{ groupItem.groupSchoolNo }}</td>
                      </tr>
                      <tr>
                        <td class="td rb">分组编号</td>
                        <td class="td">{{ groupItem.groupNo }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <div class="qrcode">
                  <qrcode-vue :value="groupItem.groupNo + ''" :size="80" level="H" />
                </div>
              </div>
              <div v-if="searchModel.templateStyle == 'normal'" class="student-con ">
                <table style="width: 100%;border: 1px solid #e5e5e5;">
                  <tbody>
                    <tr class="group-info">
                      <td class="td rb">姓名</td>
                      <td class="td rb">学籍号</td>
                      <td class="td rb">性别</td>
                      <td class="td rb">年级</td>
                      <td class="td rb">班级</td>
                      <td class="td rb">组内序号</td>
                      <td class="td rb" v-for="item in groupItem.maxProjectNames" :key="item">
                        {{ item }}
                      </td>
                    </tr>
                    <tr v-for="std in groupItem.testStudents" :key="std.studyCode" class="group-info">
                      <td class="td rb">{{ std.name }}</td>
                      <td class="td rb">{{ std.studyCode }}</td>
                      <td class="td rb">{{ std.sex == '1' ? '男' : '女' }}</td>
                      <td class="td rb">{{ std.gradeName }}</td>
                      <td class="td rb">{{ std.classesName }}</td>
                      <td class="td rb">{{ std.groupInNo }}</td>
                      <td class="td rb" v-for="item in groupItem.maxProjectNames" :key="item">

                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div v-else class="student-con ">
                <table style="width: 100%;border: 1px solid #e5e5e5;">
                  <tbody>
                    <tr class="group-info">
                      <td class="td rb">组内号</td>
                      <td class="td rb">姓名</td>
                      <td class="td rb">学籍号</td>
                      <td class="td rb">性别</td>
                      <td class="td rb">年级</td>
                      <td class="td rb">班级</td>
                      <td class="td rb" v-for="item in groupItem.projectMaxSize" :key="item">
                        {{ '项目' + item }}
                      </td>
                    </tr>
                    <tr v-for="std in groupItem.testStudents" :key="std.studyCode" class="group-info">
                      <td class="td rb">{{ std.groupInNo }}</td>
                      <td class="td rb">{{ std.name }}</td>
                      <td class="td rb">{{ std.studyCode }}</td>
                      <td class="td rb">{{ std.sex == '1' ? '男' : '女' }}</td>
                      <td class="td rb">{{ std.gradeName }}</td>
                      <td class="td rb">{{ std.classesName }}</td>
                      <td class="td rb" v-for="(item, index) in std.projectNameList" :key="item">
                        {{ item }}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div style="height: 20px;"></div>
            </div>
          </div>
        </a-spin>
      </div>
    </a-card>
  </div>

  <a-modal v-model:visible="showArrangeImportDialog" width="600px" :hide-cancel="true" :draggable="true"
    title="导入自定义编排">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        <div style="color: red;">本平台为互联网非涉密平台，严禁处理、传输国家秘密、工作秘密及敏感信息。请确认扫描、传输的文件资料不涉及上述信息。</div>
        <div>暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传</div>
      </div>
      <a-button type="link" href="/自定义编排模板.xlsx" style="margin-bottom: 10px">自定义编排模板下载</a-button>
      <Upload :uploadData="uploadData" v-model:uploadErrorList="uploadErrorList" accept=".xls,.xlsx" :draggable="true"
        action="/admin/v1/plan/apply/importCustomArrange" />
      <div class="upload-error-con" v-if="uploadErrorList && uploadErrorList.length > 0">
        <div class="title">错误信息：</div>
        <div class="upload-error-item" v-for="error in uploadErrorList" :key="error">
          {{ error }}
        </div>
      </div>
    </a-space>
  </a-modal>

  <a-modal v-model:visible="exportArrangeTicketVisible" width="400px" title="导出准考证" :footer="null">
    <a-spin :loading="exportingTicket" style="width: 100%;">
      <a-form ref="submitExportTicketForm" :model="exportTicketModel" auto-label-width
        @submit-success="sureExportArrangeTicket">
        <a-form-item field="exportArrangeTicketType" label="排序方式"
          :rules="[{ required: true, message: '请选择导出准考证排序方式' }]">
          <a-radio-group v-model="exportTicketModel.exportArrangeTicketType">
            <a-radio value="1">按分组</a-radio>
            <a-radio value="2">按班级</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="exportingTicket">确定</a-button>
            <a-button @click="exportArrangeTicketVisible = false">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>


  <a-modal v-model:visible="arrangeVisible" title="编排计划" :footer="null">
    <a-spin :loading="submiting" style="width: 100%;">
      <a-form ref="submitForm" :model="arrangeModel" @submit-success="sureArrange">
        <a-form-item field="numForGroup" label="每组人数" :rules="[{ type: 'number', required: true, message: '请输入每组人数' }]">
          <!-- <a-input-number v-model="arrangeModel.numForGroup" placeholder="请输入每组人数"></a-input-number> -->
          <a-select v-model="arrangeModel.numForGroup" placeholder="请选择每组人数">
            <a-option :value="5" label="5人"></a-option>
            <a-option :value="10" label="10人"></a-option>
            <a-option :value="15" label="15人"></a-option>
            <a-option :value="20" label="20人"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="sexGroup" label="男女分组" :rules="[{ required: true, message: '请选择男女分组方式' }]">
          <a-radio-group v-model="arrangeModel.sexGroup">
            <a-radio value="2">男女混编</a-radio>
            <a-radio value="1">男女不混编</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="classFixGroup" label="班级分组" :rules="[{ required: true, message: '请选择班级分组方式' }]">
          <a-radio-group v-model="arrangeModel.classFixGroup">
            <a-radio :value="true">班级混编</a-radio>
            <a-radio :value="false">班级不混编</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="gradeFixGroup" label="年级分组" :rules="[{ required: true, message: '请选择年级分组方式' }]">
          <a-radio-group v-model="arrangeModel.gradeFixGroup">
            <a-radio :value="true">年级混编</a-radio>
            <a-radio :value="false">年级不混编</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="submiting">确定</a-button>
            <a-button @click="arrangeVisible = false">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>

</template>

<style>
@page {
  size: auto;
  margin: 0mm;
}

.pages {
  width: 210mm;
  text-align: center;
  margin: 0 auto;
}

.pdfRef {
  border-bottom: 1px solid #e5e5e5;
  padding: 16px;
  background-color: #fff;
}

.pdfRef .title {
  text-align: center;
  font-weight: 600;
  color: #000;
  padding: 16px 0;
}

.pdfRef .group-info {
  border-bottom: 1px solid #e5e5e5;
}

.student-con {
  margin-top: 16px;
}

.rb {
  border-right: 1px solid #e5e5e5;
}

.td {
  padding: 16px 0;
  text-align: center;
  width: 100px;
  vertical-align: middle;
  color: #000;
}

.qrcode {
  text-align: center;
  padding: 10px;
}
</style>
